package howl.Servlets.cron;


import howl.model.PMF;
import howl.types.HowlUser;
import howl.types.Report;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import compiler.exceptions.HowlModelException;

import twitter4j.Twitter;
import twitter4j.TwitterException;

@SuppressWarnings("serial")
public class GenerateReports extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Properties props = new Properties(); 
        Session session = Session.getDefaultInstance(props, null); 
        
		Query query = pm.newQuery("select from howl.types.Report "
				+ "import howl.types.Report;");

		List<Report> result = (List<Report>) query.execute();

		for (int i = 0; i < result.size(); i++) {
			Report a = result.get(i);
			
			Query Userquery = pm
			.newQuery("select from howl.types.HowlUser "
					+ "where users == Param "
					+ "parameters User Param "
					+ "import howl.types.HowlUser; import com.google.appengine.api.users.User;");

			HowlUser hu = ((List<HowlUser>) Userquery.execute(a.getOwner())).get(0);
			

			
            try {
            	pm.detachCopy(a);
            	String body = null;
				try {
					body = a.generateReport();
				} catch (HowlModelException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	
            	if(body != null){
            		a.setLastrun(new Date());
            	Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("UoWhowl@googlemail.com", "Howl Admin"));
				msg.addRecipient(Message.RecipientType.TO,
				         new InternetAddress(hu.getEmailAddress(), hu.getUsers().getNickname()));
				msg.setSubject("Howl Report: " + a.getExp() + " " + a.getWhen());
	            msg.setText(body);
	            Transport.send(msg);
            	}
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
		}
		pm.close();
	}

	private String[] subArray(int start, int end, String[] s) {
		String[] ret = new String[end + 1 - start];
		for (int i = 0; i < end + 1 - start; i++) {
			ret[i] = s[start + i];
		}

		return ret;
	}
}
